package com.dlyk.handle;

import com.dlyk.bean.TUser;
import com.dlyk.constant.Constants;
import com.dlyk.result.R;
import com.dlyk.service.RedisService;
import com.dlyk.utils.JSONUtils;
import com.dlyk.utils.JWTUtils;
import com.dlyk.utils.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //登录成功，执行该方法，在该方法中返回json给前端
        TUser tUser = (TUser) authentication.getPrincipal();

        // 将tUser对象转换成Json格式数据作为负载数据放入JWT
        String userJSON = JSONUtils.toJSON(tUser);
        // 生成JWT令牌
        String jwt = JWTUtils.createJWT(userJSON);

        // 将token信息放入redis中
        redisService.setValue(Constants.REDIS_JWT_KEY+tUser.getId(),jwt);

        // 设置JWT的过期时间(如果保存过期事件为7天，否则过期事件为30分钟)
        String rememberMe = request.getParameter("rememberMe");
        if (Boolean.parseBoolean(rememberMe)){
            redisService.expire(Constants.REDIS_JWT_KEY+tUser.getId(),Constants.EXPIRE_TIME, TimeUnit.SECONDS);
        }else {
            redisService.expire(Constants.REDIS_JWT_KEY+tUser.getId(),Constants.DEFAULT_EXPIRE_TIME,TimeUnit.SECONDS);
        }

        // 登录成功的统一结果
        R result = R.OK(jwt);

        // 把R对象转换成Json
        String resultJSON = JSONUtils.toJSON(result);

        //把R以json返回给前端
        ResponseUtils.write(response, resultJSON);
    }
}
